<template>

	<!--顶部新增、查询-->
    <div style="margin-bottom: 10px;">
        <el-button type="primary" style="margin-right: 10px;" @click= "AddEmployeeClick">新增员工</el-button>
        <el-input v-model="EmployeeSearchInput" style="width: 240px" placeholder="按员工编号搜索" :prefix-icon="Search"/>
    </div>

	<!--员工数据展示表格-->
    <el-table :data="GetEmployeeData" style="width: 100%" highlight-current-row>
        <el-table-column fixed prop="employeeID" label="员工编号" align="center"/>
        <el-table-column prop="employeeName" label="员工姓名" align="center"/>
        <el-table-column prop="employeeSex" label="性别" align="center">
            <template #default="scope">
                {{ scope.row.employeeSex }}
            </template>
        </el-table-column>
        <el-table-column prop="employeeAge" label="年龄" align="center"/>
        <el-table-column prop="employeePosition" label="职位" align="center" />
        <el-table-column prop="employeePhone" label="联系电话" align="center" />
        <el-table-column label="创建时间" width="160" align="center">
            <template #default="scope">
                {{ formatDate(scope.row.createTime) }}
            </template>
        </el-table-column>
        <el-table-column fixed="right" label="员工操作" min-width="120" align="center">
            <template #default="ThisRowData">
                <el-button size="small" @click="EditEmployeeClick(ThisRowData.row)">修改</el-button>
                <el-button size="small" type="danger" @click="DeleteEmployeeClick(ThisRowData.row)">删除</el-button>
            </template>
        </el-table-column>

        <template #empty>
            <el-empty description="暂无员工数据" />
        </template>
    </el-table>

    <!-- 删除对话框 -->
    <el-dialog v-model="DeleteEmployeeDialog" title="员工删除提示" width="500">
        <span>是否确定删除该员工？</span><br>
        <span>员工编号: {{ RowEmployeeData.employeeID }}</span><br>
        <span>员工姓名: {{ RowEmployeeData.employeeName }}</span><br>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="DeleteEmployeeDialog = false">取消</el-button>
                <el-button type="primary" @click="DeleteEmployee">确定</el-button>
            </div>
        </template>
    </el-dialog>

    <!-- 修改对话框 -->
    <el-dialog v-model="EditEmployeeDialog" title="员工信息修改" width="500">
        <el-form :model="PutEmployeeData" label-width="80px">
            <el-form-item label="员工编号">
                <el-input v-model="PutEmployeeData.employeeID" disabled placeholder="员工编号" />
            </el-form-item>
            <el-form-item label="姓名">
                <el-input v-model="PutEmployeeData.employeeName" placeholder="请输入员工姓名" />
            </el-form-item>
            <el-form-item label="性别">
                <el-radio-group v-model="PutEmployeeData.employeeSex">
                    <el-radio label="男">男</el-radio>
                    <el-radio label="女">女</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="年龄">
                <el-input v-model.number="PutEmployeeData.employeeAge" type="number" placeholder="请输入员工年龄" />
            </el-form-item>
            <el-form-item label="职位">
                <el-select v-model="PutEmployeeData.employeePosition" placeholder="请选择职位">
                    <el-option v-for="item in PositionOptions" :key="item.value" :label="item.label"
                        :value="item.value" />
                </el-select>
            </el-form-item>
            <el-form-item label="联系电话">
                <el-input v-model="PutEmployeeData.employeePhone" placeholder="请输入11位手机号码" :pattern="phonePattern"
                    :rules="[{ required: true, message: '请输入有效手机号', trigger: 'blur' }]" />
            </el-form-item>
            
            <!-- 新增：只读的创建时间显示 -->
            <el-form-item label="创建时间">
                <el-input v-model="PutEmployeeData.createTime" disabled placeholder="创建时间" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="EditEmployeeDialog = false">取消</el-button>
                <el-button type="primary" @click="PutEmployee">确定</el-button>
            </div>
        </template>
    </el-dialog>

    <!-- 新增对话框 -->
    <el-dialog v-model="AddEmployeeDialog" title="添加新员工" width="500">
        <el-form :model="PostEmployeeData" label-width="80px">
            <el-form-item label="姓名">
                <el-input v-model="PostEmployeeData.employeeName" placeholder="请输入员工姓名"
                    :rules="[{ required: true, message: '姓名必填', trigger: 'blur' }]" />
            </el-form-item>
            <el-form-item label="性别">
                <el-radio-group v-model="PostEmployeeData.employeeSex">
                    <el-radio label="男">男</el-radio>
                    <el-radio label="女">女</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="年龄">
                <el-input v-model.number="PostEmployeeData.employeeAge" type="number" placeholder="请输入员工年龄" />
            </el-form-item>
            <el-form-item label="职位">
                <el-select v-model="PostEmployeeData.employeePosition" placeholder="请选择职位"
                    :rules="[{ required: true, message: '职位必填', trigger: 'blur' }]">
                    <el-option v-for="item in PositionOptions" :key="item.value" :label="item.label"
                        :value="item.value" />
                </el-select>
            </el-form-item>
            <el-form-item label="联系电话">
                <el-input v-model="PostEmployeeData.employeePhone" placeholder="请输入11位手机号码" :pattern="phonePattern"
                    :rules="[{ required: true, message: '请输入有效手机号', trigger: 'blur' }]" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="AddEmployeeDialog = false">取消</el-button>
                <el-button type="primary" @click="PostEmployee">确定</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script lang='ts' setup name='Employee'>

// 导入必要组件
import axios from 'axios';
import { reactive, ref, onMounted, watch } from 'vue';
import { ElNotification } from 'element-plus'
import { Search } from '@element-plus/icons-vue'

// 导入类型
import { type Employee } from '@/types';

// 对话框状态
const DeleteEmployeeDialog = ref(false);
const EditEmployeeDialog = ref(false);
const AddEmployeeDialog = ref(false);

// 生命周期钩子
onMounted(async () => {
    await GetEmployees();
});

// 表格单行员工数据
const RowEmployeeData = reactive<Employee>({});

// 职位选项
const PositionOptions = ref<{ label: string; value: string }[]>([
    { label: '收银员', value: '收银员' },
    { label: '理货员', value: '理货员' },
    { label: '管理员', value: '管理员' },
    { label: '主管', value: '主管' },
    { label: '保洁员', value: '保洁员' },
]);

// 手机号正则
const phonePattern = /^1[3-9]\d{9}$/;

// 格式化日期函数
const formatDate = (dateStr: string | undefined) => {
    if (!dateStr) return '-';
    // 处理ISO格式日期
    if (dateStr.includes('T')) {
        return dateStr.split('T')[0]; // 提取日期部分
    }
    return dateStr; // 已经是格式化好的日期字符串
};

// 添加员工回调
function AddEmployeeClick(){
    PostEmployeeData.employeeSex = '男';
    AddEmployeeDialog.value = true;
};

// 修改员工回调
async function EditEmployeeClick(row: Employee){
    try {
        const response = await axios.get<{ data: Employee }>(`/api/employee/${row.employeeID}`);
        console.log('获取员工信息:', response.data);
        PutEmployeeData.employeeID = response.data.data.employeeID;
        PutEmployeeData.employeeName = response.data.data.employeeName;
        PutEmployeeData.employeeSex = response.data.data.employeeSex;
        PutEmployeeData.employeeAge = response.data.data.employeeAge;
        PutEmployeeData.employeePosition = response.data.data.employeePosition;
        PutEmployeeData.employeePhone = response.data.data.employeePhone;
        PutEmployeeData.createTime = response.data.data.createTime; // 获取后端生成的创建时间
        EditEmployeeDialog.value = true;
    } catch (error) {
        ElNotification.error({ message: '获取员工信息失败' });
    }
};

// 删除员工回调
function DeleteEmployeeClick(row: Employee){
    RowEmployeeData.employeeID = row.employeeID!;
    RowEmployeeData.employeeName = row.employeeName!;
    DeleteEmployeeDialog.value = true;
};

// GET ------------------------------------------ GET //

// GET: 获取的员工数据
const GetEmployeeData = ref<Employee[]>([]);

// GET: 获取员工数据
async function GetEmployees(){
    try {
        const response = await axios.get<{ data: Employee[] }>('/api/employee');
        console.log('获取员工数据:', response.data.data);
        GetEmployeeData.value = response.data.data || [];
    } catch (error) {
        ElNotification.error({ message: '获取员工列表失败' });
        console.error('fetchEmployees error:', error);
    }
};

// GET: 获取编号员工数据
async function GetEmployeesById(){
    try {
        const response = await axios.get<{ data: Employee[] }>(`/api/employee/${EmployeeSearchInput}`);
        console.log('获取员工数据:', response.data.data);
        GetEmployeeData.value = response.data.data || [];
    } catch (error) {
        ElNotification.error({ message: '获取员工列表失败' });
        console.error('fetchEmployees error:', error);
    }
};

// 输入框接收到的供应商编号
let EmployeeSearchInput = ref('')

// 随时查询
watch(
	EmployeeSearchInput, (New, Old) => {
		GetEmployeesById()
	}
)

// POST ------------------------------------------ POST //

// POST: 添加的数据对象
const PostEmployeeData = reactive<Employee>({
    employeeSex: '男',
});

async function PostEmployee(){
    try {
        // 发送请求到后端创建新员工（不包含createTime参数）
        const response = await axios.post('/api/employee', {
            employeeName: PostEmployeeData.employeeName,
            employeeSex: PostEmployeeData.employeeSex,
            employeeAge: PostEmployeeData.employeeAge,
            employeePosition: PostEmployeeData.employeePosition,
            employeePhone: PostEmployeeData.employeePhone,
        });
        
        // 显示成功消息并刷新表格
        ElNotification.success({ message: '新员工添加成功' });
        AddEmployeeDialog.value = false;
        await GetEmployees();
    } catch (error) {
        // 显示错误消息
        ElNotification.error({ message: '新员工添加失败' });
    }
}

// PUT ------------------------------------------ PUT //

// PUT: 修改的数据对象
const PutEmployeeData = reactive<Employee>({
    employeeSex: '男',
});

// PUT: 修改数据对象
async function PutEmployee(){
    try {
        await axios.put(`/api/employee`, {
            employeeID: PutEmployeeData.employeeID,
            employeeName: PutEmployeeData.employeeName,
            employeeSex: PutEmployeeData.employeeSex,
            employeeAge: PutEmployeeData.employeeAge,
            employeePosition: PutEmployeeData.employeePosition,
            employeePhone: PutEmployeeData.employeePhone,
        });
        ElNotification.success({ message: '员工信息修改成功' });
        EditEmployeeDialog.value = false;
        await GetEmployees();
    } catch (error) {
        ElNotification.error({ message: '员工信息修改失败' });
    }
};

// DELETE ------------------------------------------ DELETE //

// DELETE: 删除员工
async function DeleteEmployee(){
    try {
        await axios.delete(`/api/employee/${RowEmployeeData.employeeID}`);
        ElNotification.success({ message: '员工删除成功' });
        DeleteEmployeeDialog.value = false;
        await GetEmployees();
    } catch (error) {
        ElNotification.error({ message: '员工删除失败' });
    }
};

</script>

<style scoped>

/* 表格居中设置 */
.el-table-column {
    text-align: center;
}

</style>